package com.jcli.jb51_net.article._获取屏幕中颜色;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 public class ColorPicker01 extends JFrame {
    private JPanel colorPanel;
    private JLabel infoLabel;
     public ColorPicker01() {
        setTitle("颜色选择器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
         colorPanel = new JPanel();
        colorPanel.setPreferredSize(new Dimension(800, 800));
        add(colorPanel, BorderLayout.CENTER);
         infoLabel = new JLabel("点击屏幕来获取颜色");
        add(infoLabel, BorderLayout.SOUTH);
         addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Color color = getColorAt(e.getX(), e.getY());
                colorPanel.setBackground(color);
                infoLabel.setText("当前颜色: " + color.toString());
            }
        });
         pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
     private Color getColorAt(int x, int y) {
        try {
            Robot robot = new Robot();
            return robot.getPixelColor(x, y);
        } catch (AWTException e) {
            e.printStackTrace();
            return null;
        }
    }
     public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ColorPicker01());
    }
}